import request from './request.js'

/**
 * 支付服务 - 最佳实践指南
 * 
 * 🔧 支付流程步骤：
 * 1. 调用 payOrder() 获取支付参数
 * 2. 验证支付参数完整性
 * 3. 调用 uni.requestPayment() 唤起微信支付
 * 4. 处理支付回调结果
 * 5. 轮询支付状态确认
 * 
 * ⚠️ 常见错误：
 * - 获取支付参数后未调用 uni.requestPayment()
 * - 支付参数格式不正确
 * - 未处理支付取消情况
 * - 缺少支付状态轮询
 * - 缺少 total_fee 参数（微信支付JSAPI必需）
 * 
 * ✅ 修复方案：
 * - 完整的支付参数验证
 * - 正确的错误处理机制
 * - 支付状态轮询确认
 * - 用户友好的提示信息
 * - 确保包含 total_fee 参数
 */

// 支付服务
export const payService = {
  // 创建支付订单
  async createPayment(orderId) {
    return request({
      url: 'Pay/create',
      method: 'POST',
      data: { orderId }
    })
  },

  // 查询支付结果
  async queryPayment(orderId) {
    return request({
      url: `Pay/query/${orderId}`,
      method: 'GET'
    })
  },

  // 获取支付记录列表
  async getPaymentRecords(params = {}) {
    return request({
      url: 'Pay/records',
      method: 'GET',
      data: params
    })
  },

  // 获取支付记录详情
  async getPaymentRecordDetail(paymentId) {
    return request({
      url: `Pay/record/${paymentId}`,
      method: 'GET'
    })
  },

  // 获取订单支付信息
  async getOrderPaymentInfo(orderId) {
    return request({
      url: `Pay/order/${orderId}`,
      method: 'GET'
    })
  },

  // 申请退款
  async applyRefund(params) {
    return request({
      url: 'Pay/refund',
      method: 'POST',
      data: params
    })
  },

  // 获取退款记录列表
  async getRefundRecords(params = {}) {
    return request({
      url: 'Pay/refunds',
      method: 'GET',
      data: params
    })
  },

  // 获取退款记录详情
  async getRefundRecordDetail(refundId) {
    return request({
      url: `Pay/refund/${refundId}`,
      method: 'GET'
    })
  },

  // 查询退款状态
  async queryRefundStatus(refundId) {
    return request({
      url: `Pay/refund/status/${refundId}`,
      method: 'GET'
    })
  },

  // 获取支付统计
  async getPaymentStatistics(params = {}) {
    return request({
      url: 'Pay/statistics',
      method: 'GET',
      data: params
    })
  },

  // 获取支付配置
  async getPaymentConfig() {
    return request({
      url: 'Pay/config',
      method: 'GET'
    })
  },

  // 更新支付配置
  async updatePaymentConfig(config) {
    return request({
      url: 'Pay/config',
      method: 'PUT',
      data: config
    })
  },

  // 获取可用支付方式
  async getPaymentMethods() {
    return request({
      url: 'Pay/methods',
      method: 'GET'
    })
  },

  // 获取支付限额
  async getPaymentLimits() {
    return request({
      url: 'Pay/limits',
      method: 'GET'
    })
  },

  // 支付验证
  async verifyPayment(params) {
    return request({
      url: 'Pay/verify',
      method: 'POST',
      data: params
    })
  },

  // 风控检查
  async riskCheck(params) {
    return request({
      url: 'Pay/risk/check',
      method: 'POST',
      data: params
    })
  },

  // 安全确认
  async securityConfirm(params) {
    return request({
      url: 'Pay/security/confirm',
      method: 'POST',
      data: params
    })
  },

  // 获取支付日志
  async getPaymentLogs(params = {}) {
    return request({
      url: 'Pay/logs',
      method: 'GET',
      data: params
    })
  },

  // 获取支付错误日志
  async getPaymentErrors(params = {}) {
    return request({
      url: 'Pay/errors',
      method: 'GET',
      data: params
    })
  },

  // 记录支付日志
  async logPayment(params) {
    return request({
      url: 'Pay/log',
      method: 'POST',
      data: params
    })
  },

  // 获取待支付订单
  async getPendingOrders(params = {}) {
    return request({
      url: 'Order/pending',
      method: 'GET',
      data: params
    })
  },

  // 订单支付
  async payOrder(orderNo, params = {}) {
    try {
      // 验证支付参数
      validatePaymentParams(params);
      
      return request({
        url: `Order/${orderNo}/pay`,
        method: 'POST',
        data: params
      })
    } catch (error) {
      console.error('支付参数验证失败:', error);
      throw error;
    }
  },

  // 支付超时处理
  async handlePaymentTimeout(orderId) {
    return request({
      url: `Order/${orderId}/timeout`,
      method: 'PUT'
    })
  },

  // 支付状态轮询
  async pollPaymentStatus(orderId, maxAttempts = 10) {
    return new Promise((resolve, reject) => {
      let attempts = 0
      
      const poll = async () => {
        try {
          const res = await this.queryPayment(orderId)
          
          if (res.success) {
            const status = res.data.payStatus
            
            if (status === 'SUCCESS') {
              resolve(res.data)
            } else if (status === 'FAILED') {
              reject(new Error('支付失败'))
            } else if (attempts < maxAttempts) {
              attempts++
              setTimeout(poll, 2000) // 2秒后重试
            } else {
              reject(new Error('支付超时'))
            }
          } else {
            reject(new Error(res.message || '查询支付状态失败'))
          }
        } catch (error) {
          reject(error)
        }
      }
      
      poll()
    })
  },

  // 微信支付调用
  async wxPay(paymentData) {
    return new Promise((resolve, reject) => {
      // 验证支付参数
      if (!paymentData || !paymentData.timeStamp || !paymentData.nonceStr || !paymentData.package || !paymentData.paySign) {
        reject(new Error('支付参数不完整'));
        return;
      }

      uni.requestPayment({
        timeStamp: paymentData.timeStamp,
        nonceStr: paymentData.nonceStr,
        package: paymentData.package,
        signType: paymentData.signType || 'MD5',
        paySign: paymentData.paySign,
        success: (res) => {
          console.log('微信支付成功:', res);
          resolve(res);
        },
        fail: (err) => {
          console.error('微信支付失败:', err);
          
          // 处理不同的错误类型
          if (err.errMsg) {
            if (err.errMsg.includes('cancel')) {
              reject(new Error('用户取消支付'));
            } else if (err.errMsg.includes('fail')) {
              reject(new Error('支付失败'));
            } else {
              reject(new Error(err.errMsg));
            }
          } else {
            reject(new Error('支付调用失败'));
          }
        }
      });
    });
  },

  // 完整的支付流程
  async completePayment(orderId, paymentData) {
    try {
      // 1. 调用微信支付
      await this.wxPay(paymentData);
      
      // 2. 轮询支付状态
      const result = await this.pollPaymentStatus(orderId);
      
      return {
        success: true,
        data: result,
        message: '支付成功'
      };
    } catch (error) {
      return {
        success: false,
        message: error.message || '支付失败',
        error: error
      };
    }
  },

  // 获取支付统计图表数据
  async getPaymentChartData(params = {}) {
    return request({
      url: 'Pay/statistics/chart',
      method: 'GET',
      data: params
    })
  },

  // 获取月度支付统计
  async getMonthlyStatistics(params = {}) {
    return request({
      url: 'Pay/statistics/monthly',
      method: 'GET',
      data: params
    })
  },

  // 获取支付趋势数据
  async getPaymentTrend(params = {}) {
    return request({
      url: 'Pay/statistics/trend',
      method: 'GET',
      data: params
    })
  },

  // 导出支付记录
  async exportPaymentRecords(params = {}) {
    return request({
      url: 'Pay/records/export',
      method: 'GET',
      data: params
    })
  },

  // 导出退款记录
  async exportRefundRecords(params = {}) {
    return request({
      url: 'Pay/refunds/export',
      method: 'GET',
      data: params
    })
  },

  // 撤销退款
  async cancelRefund(refundId) {
    return request({
      url: `Pay/refund/${refundId}/cancel`,
      method: 'PUT'
    })
  },

  // 测试API调用 - 用于调试
  async testApi() {
    try {
      // 测试调用支付API
      const testRes = await request({
        url: 'Order/202506212326539171/pay',
        method: 'POST',
        data: {
          amount: 200,
          total_fee: 200, // 添加 total_fee 参数，微信支付JSAPI必需
          description: '测试订单支付'
        }
      });
      
      return {
        success: true,
        message: '测试API调用成功',
        data: testRes,
        timestamp: new Date().toLocaleString()
      };
    } catch (error) {
      return {
        success: false,
        message: error.message || '测试API调用失败',
        error: error,
        timestamp: new Date().toLocaleString()
      };
    }
  },

  // 创建APP支付参数
  async createAppPayment(orderNo) {
    try {
      const response = await request({
        url: 'WxPay/create-app-payment',
        method: 'POST',
        data: { orderNo }
      });
      return response;
    } catch (error) {
      console.error('创建支付参数失败:', error);
      throw error;
    }
  },

  // 查询支付状态
  async queryPaymentStatus(orderNo) {
    try {
      const response = await request({
        url: 'WxPay/query',
        method: 'GET',
        data: { orderNo }
      });
      return response;
    } catch (error) {
      console.error('查询支付状态失败:', error);
      throw error;
    }
  },

  // 关闭支付订单
  async closePayment(orderNo) {
    try {
      const response = await request({
        url: 'WxPay/close',
        method: 'POST',
        data: { orderNo }
      });
      return response;
    } catch (error) {
      console.error('关闭支付订单失败:', error);
      throw error;
    }
  },

  // 获取支付记录
  async getPaymentRecord(orderNo) {
    try {
      const response = await request({
        url: 'WxPay/payment-record',
        method: 'GET',
        data: { orderNo }
      });
      return response;
    } catch (error) {
      console.error('获取支付记录失败:', error);
      throw error;
    }
  },

  // 获取退款记录
  async getRefundRecord(refundNo) {
    try {
        const response = await request({
        url: 'WxPay/refund-record',
        method: 'GET',
        data: { refundNo }
      });
      return response;
    } catch (error) {
      console.error('获取退款记录失败:', error);
      throw error;
    }
  }
}

// 支付状态常量
export const PAYMENT_STATUS = {
  PENDING: 0,    // 待支付
  SUCCESS: 1,    // 支付成功
  FAILED: 2,     // 支付失败
  CLOSED: 3,     // 已关闭
  REFUNDED: 4    // 已退款
}

// 退款状态常量
export const REFUND_STATUS = {
  PROCESSING: 0, // 处理中
  SUCCESS: 1,    // 退款成功
  FAILED: 2,     // 退款失败
  CANCELLED: 3   // 已撤销
}

// 支付方式常量
export const PAYMENT_METHODS = {
  WXPAY: 'WXPAY',     // 微信支付
  ALIPAY: 'ALIPAY',   // 支付宝
  BALANCE: 'BALANCE'  // 余额支付
}

// 支付状态文本映射
export const PAYMENT_STATUS_TEXT = {
  [PAYMENT_STATUS.PENDING]: '待支付',
  [PAYMENT_STATUS.SUCCESS]: '支付成功',
  [PAYMENT_STATUS.FAILED]: '支付失败',
  [PAYMENT_STATUS.CLOSED]: '已关闭',
  [PAYMENT_STATUS.REFUNDED]: '已退款'
}

// 退款状态文本映射
export const REFUND_STATUS_TEXT = {
  [REFUND_STATUS.PROCESSING]: '处理中',
  [REFUND_STATUS.SUCCESS]: '退款成功',
  [REFUND_STATUS.FAILED]: '退款失败',
  [REFUND_STATUS.CANCELLED]: '已撤销'
}

// 支付方式文本映射
export const PAYMENT_METHOD_TEXT = {
  [PAYMENT_METHODS.WXPAY]: '微信支付',
  [PAYMENT_METHODS.ALIPAY]: '支付宝',
  [PAYMENT_METHODS.BALANCE]: '余额支付'
}

// 支付参数验证函数
const validatePaymentParams = (params) => {
  const requiredParams = ['amount', 'total_fee', 'description'];
  const missingParams = [];
  
  requiredParams.forEach(param => {
    if (!params[param]) {
      missingParams.push(param);
    }
  });
  
  if (missingParams.length > 0) {
    throw new Error(`支付参数不完整，缺少: ${missingParams.join(', ')}`);
  }
  
  // 验证金额格式
  if (typeof params.amount !== 'number' || params.amount <= 0) {
    throw new Error('支付金额必须为正数');
  }
  
  if (typeof params.total_fee !== 'number' || params.total_fee <= 0) {
    throw new Error('total_fee 必须为正数');
  }
  
  // 确保 total_fee 与 amount 一致
  if (params.amount !== params.total_fee) {
    throw new Error('amount 与 total_fee 必须一致');
  }
  
  return true;
}; 